package com.clannad.eduservice.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.clannad.eduservice.entity.EduSubject;
import com.clannad.eduservice.entity.excel.SubjectData;
import com.clannad.eduservice.service.EduSubjectService;
import com.clannad.servicebase.exceptionhandler.GuliException;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService eduSubjectService;

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    public SubjectExcelListener() {}


    //读取excel内容
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null){
            throw new GuliException(20001,"文件为空");
        }
        //判断一级分类是否重复
        EduSubject eduSubject = this.exitOneSubject(eduSubjectService, subjectData.getOneSubject());
        if(eduSubject==null){
            eduSubject=new EduSubject();
            eduSubject.setParentId("0");
            eduSubject.setTitle(subjectData.getOneSubject());
            eduSubjectService.save(eduSubject);
        }
        //获取一级分类的id
        String pid=eduSubject.getId();
        EduSubject eduTwoSubject = this.exitTwoSubject(eduSubjectService, subjectData.getTwoSubject(), pid);
        if(eduTwoSubject==null){
            eduTwoSubject=new EduSubject();
            eduTwoSubject.setParentId(pid);
            eduTwoSubject.setTitle(subjectData.getTwoSubject());
            eduSubjectService.save(eduTwoSubject);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断一级分类是否重复
    private EduSubject exitOneSubject(EduSubjectService eduSubjectService,String name){
        LambdaQueryWrapper<EduSubject> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EduSubject::getTitle,name);
        lambdaQueryWrapper.eq(EduSubject::getParentId,0);
        EduSubject oneSubject = eduSubjectService.getOne(lambdaQueryWrapper);
        return oneSubject;
    }

    //判断二级分类是否重复
    private EduSubject exitTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        LambdaQueryWrapper<EduSubject> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EduSubject::getTitle,name);
        lambdaQueryWrapper.eq(EduSubject::getParentId,pid);
        EduSubject twoSubject = eduSubjectService.getOne(lambdaQueryWrapper);
        return twoSubject;
    }
}
